package cqut.wys;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

/**
 * WebSocket服务端
 * @author wuyoushan@zbj.com
 * @date 2017/3/17.
 */
public class WebServer extends WebSocketServer{

    public WebServer(InetSocketAddress address) {
        super(address);
        System.out.println("InetSocketAddress地址:" + address);
    }

    public WebServer(int port) {
        super(new InetSocketAddress(port));
        System.out.println("端口号:" + port);
    }

    /**
     * 触发连接事件
     * @param conn
     * @param handshake
     */
    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        System.out.println("WebClient连接服务成功");
    }

    /**
     * 触发关闭连接事件
     * @param conn
     * @param code
     * @param reason
     * @param remote
     */
    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        System.out.println("WebClient断开服务成功");
    }

    /**
     * 客户端发送消息到服务器时触发的事件
     * @param conn
     * @param message
     */
    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("客户端发送过来的消息"+message);
        //发送给客户端的信息
        conn.send("WebSocketServer发送的信息");
    }

    /**
     * 触发异常事件
     * @param conn
     * @param ex
     */
    @Override
    public void onError(WebSocket conn, Exception ex) {
        System.out.println("WebSocketServer异常:" + ex.toString());
    }
}
